/*******************************************************************************
 * 文件名: ZxingCode.java
 * 描    述: 二维码
 * 创建人: Dean Huang(hudi-112@163.com)
 * 日　期: 2018-02-11
 * 描　述: 文件描述
 * 版　本: 1.0
 *******************************************************************************/

package com.z1.core.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class ZxingCode {
	
	private static final Logger logger = Logger.getLogger(ZxingCode.class);
	
    private static final int WIDTH = 400; // 二维码宽
    private static final int HEIGHT = 400; // 二维码高

    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = null;
    static {
    	createHints();
    }
    
    
    private static final void createHints() {
    	if (null == hints) {
    		hints = new HashMap<EncodeHintType, Object>();
    		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
    		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
    		hints.put(EncodeHintType.MARGIN, 0);
    	}
    }

    /**
     * 生成二维码
     * @param logoFile log图片
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @return
     */
    public static BufferedImage drawQRCodeByLogoFile(File logoFile, String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoFile(logoFile, qrUrl, note, WIDTH, HEIGHT);
    }
    public static BufferedImage drawQRCodeByLogoFile(File logoFile, String qrUrl, String note, int w, int h) throws Exception {
    	if (null != logoFile && logoFile.exists()) {
    		InputStream input = new FileInputStream(logoFile);
    		return drawQRCodeByLogoStream(input, qrUrl, note, w, h);
    	}
    	return drawQRCodeByLogoStream(null, qrUrl, note, w, h);
    }
    
    
    /**
     * 生成二维码
     * @param logoInput log图片数据流
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @return
     * @throws Exception
     */
    public static BufferedImage drawQRCodeByLogoStream(InputStream logoInput, String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoStream(logoInput, qrUrl, note, WIDTH, HEIGHT);
    }
    public static BufferedImage drawQRCodeByLogoStream(InputStream logoInput, String qrUrl, String note, int w, int h) throws Exception {
//    	createHints();
    	
    	MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    	// 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
    	BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, w, h, hints);
    	
    	//去白边
    	int[] rec = bm.getEnclosingRectangle();
    	int resWidth = rec[2] + 1;
    	int resHeight = rec[3] + 1;
    	BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
    	resMatrix.clear();
    	for (int i = 0; i < resWidth; i++) {  
    	    for (int j = 0; j < resHeight; j++) {  
    	        if (bm.get(i + rec[0], j + rec[1])) { 
    	             resMatrix.set(i, j); 
    	        } 
    	    }  
    	}  
    	
    	BufferedImage image = new BufferedImage(resWidth, resHeight, BufferedImage.TYPE_INT_ARGB);
    	// 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
    	for (int x = 0; x < resWidth; x++) {
    		for (int y = 0; y < resHeight; y++) {
    			image.setRGB(x, y, resMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
    		}
    	}
    	
    	int width = image.getWidth();
    	int height = image.getHeight();
    	try {
    		if (null != logoInput) {
//    			logoInput = ZxingCode.class.getResourceAsStream("logo.png");
    			// 构建绘图对象
    			Graphics2D g = image.createGraphics();
    			// 读取Logo图片
    			BufferedImage logo = ImageIO.read(logoInput);
    			// 开始绘制logo图片
    			g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
    			g.dispose();
    			logo.flush();
    		}
    	}
    	catch (Throwable e) {
    		logger.error("zxingCode get logo input err", e);
    	}
    	finally {
    		if (null != logoInput) {
    			try { logoInput.close(); }
            	catch (Throwable ex) { }
    		}
    	}
    	// 自定义文本描述
    	if (null != note && !note.trim().equals("")) {
    		// 新的图片，把带logo的二维码下面加上文字
    		BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
    		Graphics2D outg = outImage.createGraphics();
    		// 画二维码到新的面板
    		outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
    		// 画文字到新的面板
    		outg.setColor(Color.BLACK);
    		outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
    		int strWidth = outg.getFontMetrics().stringWidth(note);
    		if (strWidth > 399) {
    			// 长度过长就截取前面部分
    			// 长度过长就换行
    			String note1 = note.substring(0, note.length() / 2);
    			String note2 = note.substring(note.length() / 2, note.length());
    			int strWidth1 = outg.getFontMetrics().stringWidth(note1);
    			int strWidth2 = outg.getFontMetrics().stringWidth(note2);
    			outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
    			BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
    			Graphics2D outg2 = outImage2.createGraphics();
    			outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
    			outg2.setColor(Color.BLACK);
    			outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
    			outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
    			outg2.dispose();
    			outImage2.flush();
    			outImage = outImage2;
    		}
    		else {
    			// 画文字
    			outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); 
    		}
    		outg.dispose();
    		outImage.flush();
    		image = outImage;
    	}
    	image.flush();
    	return image;
    }
    
    /**
     * 生成二维码至文件
     * @param codeFile 二维码文件
     * @param logoFile log图片
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static void drawQRCodeByLogoFileToFile(File codeFile, File logoFile, String qrUrl, String note) throws Exception {
    	drawQRCodeByLogoFileToFile(codeFile, logoFile, qrUrl, note, WIDTH, HEIGHT);
    }
    public static void drawQRCodeByLogoFileToFile(File codeFile, File logoFile, String qrUrl, String note, int w, int h) throws Exception {
    	ImageIO.write(
    		drawQRCodeByLogoFile(logoFile, qrUrl, note, w, h), 
    		"png", 
    		codeFile 
    	);
    }
    /**
     * 生成二维码至文件（使用默认logo图片）
     * @param codeFile 二维码文件
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static void drawQRCodeByLogoFileToFile(File codeFile, String qrUrl, String note) throws Exception {
    	drawQRCodeByLogoFileToFile(codeFile, qrUrl, note, WIDTH, HEIGHT);
    }
    public static void drawQRCodeByLogoFileToFile(File codeFile, String qrUrl, String note, int w, int h) throws Exception {
    	ImageIO.write(
    		drawQRCodeByLogoFile(null, qrUrl, note, w, h), 
    		"png", 
    		codeFile
    	);
    }
    
    /**
     * 生成二维码至文件
     * @param codeFile 二维码文件
     * @param logoInput log图片数据流
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static void drawQRCodeByLogoStreamToFile(File codeFile, InputStream logoInput, String qrUrl, String note) throws Exception {
    	drawQRCodeByLogoStreamToFile(codeFile, logoInput, qrUrl, note, WIDTH, HEIGHT);
    }
    public static void drawQRCodeByLogoStreamToFile(File codeFile, InputStream logoInput, String qrUrl, String note, int w, int h) throws Exception {
    	ImageIO.write(
    		drawQRCodeByLogoStream(logoInput, qrUrl, note, w, h), 
    		"png", 
    		codeFile
    	);
    }
    /**
     * 生成二维码至文件（使用默认logo图片）
     * @param codeFile 二维码文件
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static void drawQRCodeByLogoStreamToFile(File codeFile, String qrUrl, String note) throws Exception {
    	drawQRCodeByLogoStreamToFile(codeFile, qrUrl, note, WIDTH, HEIGHT);
    }
    public static void drawQRCodeByLogoStreamToFile(File codeFile, String qrUrl, String note, int w, int h) throws Exception {
    	ImageIO.write(
    		drawQRCodeByLogoStream(null, qrUrl, note), 
    		"png", 
    		codeFile
    	);
    }
    
    /**
     * 生成二维码为字节数组
     * @param codeFile 二维码文件
     * @param logoFile log图片
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static byte[] drawQRCodeByLogoFileToByte(File logoFile, String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoFileToByte(logoFile, qrUrl, note, WIDTH, HEIGHT);
    }
    public static byte[] drawQRCodeByLogoFileToByte(File logoFile, String qrUrl, String note, int w, int h) throws Exception {
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	ImageIO.write(
    		drawQRCodeByLogoFile(logoFile, qrUrl, note, w, h), 
    		"png", 
    		output
    	);
    	return output.toByteArray();
    }
    /**
     * 生成二维码为字节数组（使用默认logo图片）
     * @param codeFile 二维码文件
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static byte[] drawQRCodeByLogoFileToByte(String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoFileToByte(qrUrl, note, WIDTH, HEIGHT);
    }
    public static byte[] drawQRCodeByLogoFileToByte(String qrUrl, String note, int w, int h) throws Exception {
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	ImageIO.write(
    		drawQRCodeByLogoFile(null, qrUrl, note, w, h), 
    		"png", 
    		output
    	);
    	return output.toByteArray();
    }
    
    /**
     * 生成二维码为字节数组
     * @param codeFile 二维码文件
     * @param logoInput log图片数据流
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static byte[] drawQRCodeByLogoStreamToByte(InputStream logoInput, String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoStreamToByte(logoInput, qrUrl, note, WIDTH, HEIGHT);
    }
    public static byte[] drawQRCodeByLogoStreamToByte(InputStream logoInput, String qrUrl, String note, int w, int h) throws Exception {
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	ImageIO.write(
    		drawQRCodeByLogoStream(logoInput, qrUrl, note, w, h), 
    		"png", 
    		output
    	);
    	return output.toByteArray();
    }
    /**
     * 生成二维码为字节数组（使用默认logo图片）
     * @param codeFile 二维码文件
     * @param qrUrl 二维码内容
     * @param note 二维码描述
     * @throws Exception
     */
    public static byte[] drawQRCodeByLogoStreamToByte(String qrUrl, String note) throws Exception {
    	return drawQRCodeByLogoStreamToByte(qrUrl, note, WIDTH, HEIGHT);
    }
    public static byte[] drawQRCodeByLogoStreamToByte(String qrUrl, String note, int w, int h) throws Exception {
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	ImageIO.write(
    		drawQRCodeByLogoStream(null, qrUrl, note, w, h), 
    		"png", 
    		output
    	);
    	return output.toByteArray();
    }
    
}